#ifdef WX_PRECOMP
#include "wx_pch.h"
#else
#include <wx/wx.h>
#endif //WX_PRECOMP

#include "lua_output_wrapper.h"

const char LuaOutputWrapper::className[] = "LuaOutputWrapper";

Lunar<LuaOutputWrapper>::RegType LuaOutputWrapper::methods[] = {
  LUNAR_DECLARE_METHOD(LuaOutputWrapper, print),
  {0,0}
};

LuaOutputWrapper::LuaOutputWrapper(lua_State *L)
{
}

int LuaOutputWrapper::print(lua_State *L)
{
  int n = lua_gettop(L);

  for (int i = 1; i <= n; ++i)
  {
    if (lua_isstring(L, i))
      Result += lua_tostring(L, i);
    else if (lua_isnil(L, i))
      Result += "nil";
    else if (lua_isboolean(L, i))
      Result += (lua_toboolean(L, i) ? "true" : "false");
    else
      Result += luaL_typename(L, i); /*, lua_topointer(L, i));*/
  }
  return 0;
}

std::string LuaOutputWrapper::GetResult() const
{
  return Result;
}

void LuaOutputWrapper::Clear()
{
  Result.clear();
}

std::auto_ptr<LuaOutputWrapper> CreateLuaOutputWrapper(lua_State *L)
{
  Lunar<LuaOutputWrapper>::Register(L);

  std::auto_ptr<LuaOutputWrapper> result(new LuaOutputWrapper(L));

  int id = Lunar<LuaOutputWrapper>::push(L, result.get());

  lua_pushliteral(L, "LuaOutputWrapperObject");
  lua_pushvalue(L, id);
  lua_settable(L, LUA_GLOBALSINDEX);

  luaL_dostring(L, "function print(...) LuaOutputWrapperObject:print(unpack(arg)); LuaOutputWrapperObject:print(\"\\n\"); end");
  luaL_dostring(L, "function printf(...) LuaOutputWrapperObject:print(string.format(unpack(arg))); end");

  return result;
}
